package com.ly.mpayment.core.util;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * ListSortUtil.java id排序工具类
 * 
 */
public class ListSortUtil<T> {

	public static final String SORTTYPE_DESC = "desc";
	public static final String SORTTYPE_ASC = "asc";
	public static final String SORT_BY_ID = "getId";
	public static final String SORT_BY_NAME = "getName";
	public static final String SORT_BY_AREANAME = "getAreaName";
	public static final String SORT_BY_SORT = "getSort";
	public static final String SORT_BY_AREACODE= "getAreacode";
	
	public void Sort(List<T> list, final String methodName,
			final String sortType) {
		Collections.sort(list, new Comparator<T>() {
			@SuppressWarnings({ "rawtypes", "unchecked" })
			public int compare(T o1, T o2) {
				int ret = 0;
				Class c1;
				Class c2;
				Method m1;
				Method m2;
				String b1;
				String b2;
				try {
					c1 = o1.getClass();
					c2 = o2.getClass();
					m1 = c1.getDeclaredMethod(methodName);
					m2 = c2.getDeclaredMethod(methodName);
					Class type = m1.getReturnType();
					if("java.lang.Integer".equals(type.getName())){
						if (SORTTYPE_DESC.equals(sortType)) {
							ret = Integer.parseInt(m2.invoke(o2).toString()) - Integer.parseInt(m1.invoke(o1).toString());
						}else{
							ret = Integer.parseInt(m1.invoke(o1).toString()) - Integer.parseInt(m2.invoke(o2).toString());
						}
					}else{
						b1 = m1.invoke(o1).toString();
						b2 = m2.invoke(o2).toString();
						if (SORTTYPE_DESC.equals(sortType)) {
							ret = b2.compareTo(b1);
						} else {
							ret = b1.compareTo(b2);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return ret;
			}

		});
	}
}
